package com.hupu.jrs.components.okhttp

import android.text.TextUtils
import com.hupu.jrs.Constants
import com.hupu.jrs.components.storage.UserStorage
import okhttp3.Interceptor
import okhttp3.Response
import java.io.IOException
import java.net.URLEncoder

/**
 * Created by Stark.Tony on 2018/3/18.
 */
class CookieInterceptor(private val mUserStorage: UserStorage) : Interceptor {

    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val original = chain.request()
        if (!TextUtils.isEmpty(mUserStorage.cookie) && !original.url()
                .toString()
                .contains("loginUsernameEmail")) {
            val request = original.newBuilder()
                    .addHeader("Cookie", "u=" + URLEncoder.encode(mUserStorage.cookie) + ";")
                    .build()
            return chain.proceed(request)
        } else {
            for (header in chain.proceed(original).headers("Set-Cookie")) {
                if (header.startsWith("u=")) {
                    val cookie = header.split(";".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[0].substring(2)
                    if (!TextUtils.isEmpty(cookie)) {
                        Constants.Cookie = cookie
                    }
                }
            }
        }
        return chain.proceed(original)
    }
}
